var Resize = new Class({
	initialize: function(){
		this.visuals = $$('.sls_resize_container .sls_resize_visual');

		if (this.visuals.length > 0)
			this.prepareVisuals(this.visuals);

		window.addEvents({
			'resize': this.fitAll.bind(this),
			'load': this.fitAll.bind(this)
		});

		this.fitAll();
	},

	prepareVisuals: function(visuals){
		visuals.each(function(visual){
			var wrapper = visual.getParent('.sls_resize_container');
			wrapper.setStyles({'position' : 'relative', 'overflow' : 'hidden'});
			visual.store('wrapper', wrapper);
			visual.set('morph', {duration:200});
			visual.setStyles({'position':'relative'});
		});
		visuals.addClass('sls_resize_added');
	},

	fitAll: function(){
		var newVisuals = $$('.sls_resize_container .sls_resize_visual:not(.sls_resize_added)');
		if (newVisuals.length > 0){
			this.prepareVisuals(newVisuals);
			this.visuals.append(newVisuals);
		}

		this.visuals.each(function(visual){
			this.fit(visual);
		}.bind(this));
	},

	fit: function(visual){
		var wrapper = visual.retrieve('wrapper');
		var wrapperSize = wrapper.measure(function(){
			return this.getDimensions();
		});
		var wrapperWidth = wrapperSize.width;
		var wrapperHeight = wrapperSize.height;

		var visualSize = visual.measure(function(){
			return this.getDimensions();
		});

		var width = visualSize.width;
		var height = visualSize.height;

		var top, left, nwidth, nheight;

		if (width == 0 || height == 0)
			return;
		nwidth = wrapperWidth;
		nheight = (height*nwidth)/width;

		top = (wrapperHeight-nheight)/2;
		left = 0
		if (top <= 0 )
			left = 0;
		else {
			top = 0;
			nheight = wrapperHeight;
			nwidth = (nheight*width)/height;
			left = (wrapperWidth-nwidth)/2;
		}

		top = parseInt(top);
		nheight = parseInt(nheight);
		nwidth = parseInt(nwidth);
		left = parseInt(left);

		if (visual.tagName == 'IFRAME')
			visual.setStyles({'width' : wrapperWidth, 'height' : wrapperHeight, 'top' : 0, 'left' : 0});
		else if (visual.hasClass('sls_resize_no_bigger') && (nwidth > width || nheight > height))
			visual.setStyles({'width' : width, 'height' : height, 'top' : 0, 'left' : 0});
		else
			visual.setStyles({'width' : nwidth, 'height' : nheight, 'top' : top, 'left' : left});
	}
});

window.addEvent('domready', function(){
	if ($$('.sls_resize_container').length > 0)
		new Resize();
});